/*********** 独立于allStore外的纯Util，禁止引入allStore ***********/
import Field from '../stores/field';
import * as API_REQ from '../apis/req';
import * as _ from './public/common';
import base from './base';
import {registerFormula} from './public/FormulaNew';

//获取浏览器版本
export const getBrowserVersion = () => {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
    if (isChrome)
        return "Chrome";

    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isEdge)
        return "Edge";
    if(isIE11)
        return "IE11";
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7)
            return "IE7";
        else if (fIEVersion == 8)
            return "IE8";
        else if (fIEVersion == 9)
            return "IE9";
        else if (fIEVersion == 10)
            return "IE10";
        else if (fIEVersion == 11)
            return "IE11";
        else
            return "IE";
    }
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器  
    if (isOpera)
        return "Opera";
    if (isFF)
        return "FF";
    if (isSafari)
        return "Safari";
    return "unident";
}

//打印耗时
export const printDuration = (params) =>{
    try{
        if(window.console){
            console.log(`请求id: ${params.requestid}`);
            console.log(`js加载耗时: ${window.JS_LOAD_DURATION || 0}毫秒`);
            console.log(`中转耗时: ${window.Route_DURATION || 0}毫秒`);
            console.log(`异步js耗时: ${window.ASYNC_DURATION || 0}毫秒`);
            console.log(`服务端耗时: ${window.SERVER_DURATION || 0}毫秒`);
            console.log(`接口耗时: ${window.API_DURATION || 0}毫秒`);
            console.log(`渲染耗时: ${window.DISPATCH_DURATION || 0}毫秒`);
            console.log(`总耗时: ${window.REQ_LOAD_DURATION / 1000 || 0}秒`);
        }
    }catch(e){}
}

//刷新列表
export const reloadListPage = (params) => {
    try {
        //刷新待办列表
        window.opener._table.reLoad(params);
    } catch (e) {}
    try {
        //刷新门户列表
        jQuery(window.opener.document).find('#btnWfCenterReload').click();
    } catch (e) {}
}

//控制转换
export const convertNull = (value, bool=true) =>{
    if(value === null || typeof value === "undefined")
        return "";
    else 
        return bool ? value.toString() : value;
}

//加载代码块及custompage
export const loadScript = () => {
    const params = base.globalStore.commonParam;
    const billIncludePage = params.billIncludePage || "";
    const hasBillIncludePage = billIncludePage !== "";
    let custompage = params.custompage || "";
    if(custompage === billIncludePage)
        custompage = "";    //避免重复加载
    let promiseList = [
        API_REQ.loadScriptContent({
            layoutid: params.modeid
        })
    ];
    if(custompage === ""){
        promiseList.push(new Promise((resolve)=>{
            resolve("");
        }));
    }else{
        promiseList.push(API_REQ.loadCustompage(custompage, params));
    }
    if(hasBillIncludePage){
        promiseList.push(API_REQ.loadCustompage(billIncludePage, params));
    }
    Promise.all(promiseList).then((result)=>{
        try{
            jQuery(".excelTempDiv #scriptArea").html("").append(manageScriptContent(result[0]));
        }catch(e){}
        try{
            jQuery(".excelTempDiv #customPageArea").html("").append(manageScriptContent(result[1]));
        }catch(e){}
        try{
            if(hasBillIncludePage){
                jQuery(".excelTempDiv #billIncludeArea").html("").append(manageScriptContent(result[2]));
            }
        }catch(e){}
        registerFormula();
        printPreViewPage();
    });
}

//弹出打印预览界面
export const printPreViewPage = () =>{
    const { browserVersion,urlParams,commonParam, } = base.globalStore;
    if(parseInt(commonParam.isprint) !== 1)
        return;
    if(urlParams.isBatchPrint === "true"){
        window.setTimeout(function(){
            //批量打印给iframe赋值高度
            const requestid = commonParam.requestid;
            const printObj = jQuery(".wf-req-print");
            const iframeObj = jQuery("iframe#request_"+requestid, window.parent.document);
            iframeObj.css("height", printObj.height()+150);
        },300);
        return;
    }
    if(urlParams.isPreView === "true")
        return;
    window.setTimeout(function(){
        if(browserVersion.indexOf("IE") > -1){
            try{
                //通过修改电脑注册表，控制IE下打印设置，默认勾选允许收缩到纸张大小
                var hkey_root = "HKEY_CURRENT_USER" ;
                var hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
                var hkey_key = "";
                var RegWsh = new ActiveXObject("WScript.Shell");
                hkey_key = "Print_Background";
                RegWsh.RegWrite(hkey_root+hkey_path+hkey_key, "yes");
                hkey_key = "Shrink_To_Fit";
                RegWsh.RegWrite(hkey_root+hkey_path+hkey_key, "yes");
            }catch(e){
                if(window.console)
                    console.log("请设置IE下允许ActiveX插件运行,"+e);
            }
            try {
                document.all.WebBrowser.ExecWB(7,1);    //IE下弹预览
            } catch(e9) {
                window.print();
            }
        }else{
            window.print();
        }
    },1000);
}

//代码块中<script id>标签转换处理
export const manageScriptContent = (content) =>{
    if(!content)
        return "";
    const arr1 = content.match(new RegExp("<script .*?id=.*?></script>", "ig")) || new Array();
    const arr2 = content.match(new RegExp("<script .*?id=.*?/>", "ig")) || new Array();
    const arr = arr1.concat(arr2);
    let appendScriptSpan = "";
    arr !== null && arr.map(v =>{
        appendScriptSpan += v.replace(new RegExp("(<|/)script","ig"), "$1span");
    });
    return content + appendScriptSpan;
}

//获取字段ID
export const getFieldid = (fieldMark) =>{
    if(fieldMark.indexOf("_") > -1)
        fieldMark = fieldMark.substring(0, fieldMark.indexOf("_"));
    if(fieldMark.indexOf("field") > -1)
        fieldMark = fieldMark.substring(5);
    return fieldMark;
}

//获取字段所属表
export const getTableMark = (fieldMark, fieldAttrMap) =>{
    const fieldid = getFieldid(fieldMark);
    let tableMark = "";
    if(fieldAttrMap.has(fieldid))
        tableMark = fieldAttrMap.get(fieldid).tableMark;
    return tableMark;
}

//获取字段基础信息
export const getFieldAttr = (fieldMark, fieldAttrMap) =>{
    const fieldid = getFieldid(fieldMark);
    let fieldAttr = null;
    if(fieldAttrMap.has(fieldid))
        fieldAttr = fieldAttrMap.get(fieldid);
    return fieldAttr;
}

//获取字段值
export const getFieldValue = (layoutStore, fieldid, rowIndex, convertNum) =>{
    const fieldObj = getFieldValObj(layoutStore, fieldid, rowIndex);
    return convertNum === true ? fieldObj.numValue : fieldObj.value;
}

//获取字段值对象
export const getFieldValObj = (layoutStore, fieldid, rowIndex) =>{
    const { fieldAttrMap,mainData,detailMap } = layoutStore;
    if(!fieldAttrMap.has(fieldid.toString())){
        if(window.console)  console.log(`getFieldValObj ${fieldid} Not Exist`);
        return null;
    }
    const tableMark = fieldAttrMap.get(fieldid.toString()).tableMark;
    const fieldMark = tableMark.indexOf("detail") === -1 ? `field${fieldid}` : `field${fieldid}_${rowIndex}`;
    return getFieldObj(fieldMark, tableMark, mainData, detailMap);
}

//获取字段值对象
export const getFieldObj = (fieldMark, tableMark, mainData, detailMap) =>{
    if(!tableMark)
        return null;
    if(tableMark.indexOf("detail") === -1)
        return getMainFieldObj(fieldMark, mainData);
    else
        return getDetailFieldObj(fieldMark, tableMark, detailMap);
}

//获取主表字段值对象
export const getMainFieldObj = (fieldMark, mainData) =>{
    let fieldObj = null;
    if(mainData.has(fieldMark))
        fieldObj = mainData.get(fieldMark);
    else
        fieldObj = new Field();
    return fieldObj;
}

//获取明细表字段值对象
export const getDetailFieldObj = (fieldMark, tableMark, detailMap) =>{
    let fieldObj = null;
    const detailObj = detailMap.get(tableMark);
    const detailData = detailObj.detailData;
    if(detailData.has(fieldMark))
        fieldObj = detailData.get(fieldMark);
    else
        fieldObj = new Field();
    return fieldObj;
}

//计算表达式结果
export const calExpressionResult = (expression) =>{
    const { propFileCfg } = base.layoutStore;
    const open_server_eval = propFileCfg && propFileCfg.open_server_eval == "1";
    let result = "";
    try{
        if(open_server_eval){
            let execSuccess = false;
            jQuery.ajax({
                type: "POST",
                async: false,
                url: "/api/workflow/reqform/doEvalExpression?expression="+encodeURIComponent(expression),
                success: function(data){
                    const dataobj = JSON.parse(_.trim(data));
                    if(dataobj && dataobj.status === true){
                        execSuccess = true;
                        result = dataobj.result;
                    }
                }
            });
            if(!execSuccess)
                result = eval(expression);
        }else{
            result = eval(expression);
        }
    }catch(e){
        if(window.console)  console.log("Eval Appear Exception:"+expression);
    }
    return result.toString();
}

//修改Store值前，做字段值处理
export const convertValueBeforeChangeStore = (value, fieldAttr) =>{
    if(_.isEmpty(fieldAttr))
        return value;
    const htmltype = fieldAttr.htmltype;
    const detailtype = fieldAttr.detailtype;
    let newValue = value;
    if(htmltype === 1){
        if(detailtype === 1){
            newValue = convertSpecialChar(newValue);
        }else{  //数值字段格式化
            newValue = convertNumberValue(newValue, fieldAttr);
        }
    }else if(htmltype === 2 && detailtype === 1){
        newValue = convertSpecialChar(newValue);
    }else if(htmltype === 3 && detailtype === 2){   //日期字段格式化
        const reg = /^\d{4}-\d{1,2}-\d{1,2}$/;
        if(!!newValue && !reg.test(newValue))
            newValue = "";
    }else if(htmltype === 3 && detailtype === 19){  //时间字段格式化
        const reg = /^\d{1,2}:\d{1,2}$/;
        if(!!newValue && !reg.test(newValue))
            newValue = "";
    }else if(htmltype === 4){   //check框只允许0/1值入库
        if(!newValue || (newValue.toString() !== "0" && newValue.toString() !== "1"))
            newValue = "0";
    }
    return newValue;
}

//修改Store时，替换特殊字符,转换成提交时需要的格式
export const convertSpecialChar = (str) =>{
    str = str.toString();
    str = str.replace(/<br>/ig, "\n");
    str = str.replace(/&nbsp;/ig, " ");
    str = str.replace(/&lt;/ig, "<");
    str = str.replace(/&gt;/ig, ">");
    str = str.replace(/&quot;/ig, "\"");
    str = str.replace(/&amp;/ig, "&");
    return str;
}

//判断值是否属于数字
export const judgeIsNumber = (val) =>{
    if(val === null || typeof val === "undefined")
        return false;
    const reg = /^(-?\d+)(\.\d+)?$/;
    return reg.test(val.toString());
}

//根据字段信息格式化字段值(浮点数位数、转千分位等)
export const convertNumberValue = (realval, fieldAttr) =>{
	if(realval === null || typeof realval === "undefined")
        return "";
    const isqfw = fieldAttr.detailtype === 5;
    if(isqfw)
        realval = realval.toString().replace(/,/g, "");
    if(!judgeIsNumber(realval))
        return "";
    return convertFloatValue(realval, fieldAttr.qfws, isqfw);
}

/**
 * 数值转换(精度、千分位)等
 * @param {String} realval   真实值
 * @param {int} decimals  精度
 * @param {Boolean} transQfw  是否千分位
 * @param {Boolean} transAbs  是否绝对值
 */
export const convertFloatValue = (realval, decimals, transQfw, transAbs) =>{
	if(!judgeIsNumber(realval))     //非数值直接返回原始值
		return realval;
    realval = realval.toString();
	var formatval = "";
	if(decimals === 0){		//需取整
		formatval = Math.round(parseFloat(realval)).toString();
	}else{
        var n = Math.pow(10, decimals);
        formatval = (Math.round(parseFloat(realval)*n)/n).toString();
		var pindex = formatval.indexOf(".");
		var pointLength = pindex>-1 ? formatval.substr(pindex+1).length : 0;	//当前小数位数
		if(decimals > pointLength){		//需补零
            if(pindex == -1)
			    formatval += ".";
			for(var i=0; i<decimals-pointLength; i++){
				formatval += "0";
			}
		}
	}
	var index = formatval.indexOf(".");
	var intPar = index>-1 ? formatval.substring(0,index) : formatval;
	var pointPar = index>-1 ? formatval.substring(index) : "";
	//取绝对值
	if(transAbs === true){		//取绝对值
		intPar = Math.abs(intPar).toString();
	}
	if(transQfw === true){				//整数位format成千分位
   		var reg1 = /(-?\d+)(\d{3})/;
        while(reg1.test(intPar)) {   
        	intPar = intPar.replace(reg1, "$1,$2");   
        } 
	}
	formatval = intPar + pointPar;
	return formatval;
}

//时间字段值补零
export const convertTimeValue = (value) =>{
    const reg = /^\d{1,2}:\d{1,2}$/;
    if(!!value && reg.test(value)){
        let arr = value.split(":");
        if(arr[0].length === 1)     arr[0] = "0"+arr[0];
        if(arr[1].length === 1)     arr[1] = "0"+arr[1];
        value = arr[0]+":"+arr[1];
    }else
        value = "";
    return value;
}

//转换系统字段名称 
export const convertSystemFieldName = (fieldname) => {
	switch(fieldname){
		case 'field-1':
			return 'requestname';
		case 'field-2':
			return 'requestlevel';
		case 'field-3':
			return 'messageType';
		case 'field-5':
			return 'chatsType';
		default:
			return fieldname;
	}
}

//获取流程干预默认值
export const getIntervenorDefaultV = (data = {}) => {
    let updateinfo = {};
    const {replacedatas = [], items = []} = data;
    if (items.length > 0) {
        items.map((item) => {
            const {labelcol, fieldcol, label, conditionType, domkey = [], browserConditionParam = {}, options = []} = item;
            if (conditionType == 'SELECT') {
                options.map((o) => {
                    if (o.selected) updateinfo[domkey[0]] = o.key;
                })
            } else if (conditionType == 'BROWSER') {
                const {replaceDatas = []} = browserConditionParam;
                let ids = [];
                replaceDatas.map((o) => {
                    ids.push(o.id);
                })
                updateinfo[domkey[0]] = ids.join(',');
            }
        });
    }
    if (replacedatas.length > 0) {
        let ids = [];
        let operatortypes = [];
        replacedatas.map(o => {
            const {id, IntervenoridType = ''} = o;
            ids.push(id);
            operatortypes.push(IntervenoridType);
        });
        updateinfo['Intervenorid'] = ids.join(',');
        updateinfo['IntervenoridType'] = operatortypes.join(',');
    }
    return updateinfo;
}